//
//  GMGroup.m
//  GroupManager
//
//  Created by 欧阳 鹏 on 11-10-16.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "GMGroup.h"
#import "GMPerson.h"
#import "ABManager.h"


@implementation GMGroup

@synthesize group, personArray, persons;

- (void)dealloc {
	if (persons) {
		[persons release];
	}
	[super dealloc];
}

+ (id)groupWithGroup:(ABRecordRef)_group {
	return [[[self alloc] initWithGroup:_group] autorelease];
}

- (id)initWithGroup:(ABRecordRef)_group {
	if (self = [super init]) {
		group = _group;
		if (!persons) {
			persons = [[NSMutableArray alloc] initWithCapacity:4];
		}
	}
	return self;
}

- (NSString*)getName {
	NSString* name = nil;
	CFStringRef value = ABRecordCopyValue(group, kABGroupNameProperty);
	if (value) {
		name = [NSString stringWithString:(NSString *)value];
		CFRelease(value);
	}
	return name;
}

- (void)setName:(NSString*)name {
	ABRecordSetValue(group, kABGroupNameProperty, name, nil);
}

- (int)getPersonCount {
	return [persons count];
}

- (void)readAllPersonsOfGroup {
	[persons removeAllObjects];
	CFArrayRef personArr = ABGroupCopyArrayOfAllMembersWithSortOrdering(group, kABPersonSortByLastName);
	if (personArr) {
		for (int i = 0; i < CFArrayGetCount(personArr); i ++) {
			ABRecordRef record = CFArrayGetValueAtIndex(personArr, i);
			GMPerson *person = [GMPerson personWithPerson:record];
			[persons addObject:person];
		}
		CFRelease(personArr);
	}
}

- (void)addMember:(ABRecordRef)member {
	GMPerson *person = [GMPerson personWithPerson:member];
	for (GMPerson *p in persons) {
		if (p.person == member) {
			return;
		}
	}
	int index = 0;
	for (; index < [persons count]; index ++) {
		GMPerson *p = [persons objectAtIndex:index];
		if (ABPersonComparePeopleByName(member, p.person, ABPersonGetSortOrdering()) == kCFCompareLessThan) {
			[persons insertObject:person atIndex:index];
			break;
		}
	}
	if (index == [persons count]) {
		[persons addObject:person];
	}
	ABGroupAddMember(group, member, nil);
	[[ABManager sharedManager] saveAddressBook];
}

- (void)removeMemberAtIndex:(NSUInteger)index {
	ABRecordRef member = ((GMPerson*)[persons objectAtIndex:index]).person;
	ABGroupRemoveMember(group, member, nil);
	[persons removeObjectAtIndex:index];
	[[ABManager sharedManager] saveAddressBook];
}

@end
